﻿@page "{id}"
@{
    ViewBag.Title = this.Article.Title;
}
@inject ArticleService _articleService
@inject SettingService _settingService
@inject CommentService _commentService
@inject IMessageSender _messageSender
@inject Microsoft.Extensions.Logging.ILoggerFactory _loggerFactory

    @using Microsoft.Extensions.Logging
@using SingleBlog.Framework

@functions{
    Article Article { get; set; }

    IEnumerable<Article> RecommandArticles { get; set; }

    GeneralSettingModel GeneralSetting { get; set; }

    public async Task OnGetAsync(int id)
    {
        this.Article = await _articleService.GetArticleAsync(id);
        if (this.Article == null)
        {

        }
        this.RecommandArticles = await _articleService.GetRecommandArticlesAsync();
        this.GeneralSetting = _settingService.GetGeneralSetting();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        var setting = _settingService.GetGeneralSetting();

        if (!setting.AllowComment)
        {
            ModelState.AddModelError("", "系统设置了不允许回复");
            return Page();
        }

        var form = Request.Form;
        var comment = new Comment
        {
            Content = form["Content"],
            ArticleId = form["ArticleId"].ToString().To<int>()
        };

        var name = (string)form["Name"];
        var email = (string)form["Email"];

        if (!ModelState.IsValid || name.IsNullOrWhiteSpace() || email.IsNullOrWhiteSpace() || !email.IsMatchEmail())
        {
            ModelState.AddModelError("", "提交内容不正确");
            return Page();
        }

        comment.Content = comment.Content.Replace("\r\n", "<br/>");

        comment.AnonymouseUserInfo = JsonConvert.SerializeObject(new AnonymousUserModel { Name = name, Email = email });

        var article = await _articleService.GetArticleAsync(comment.ArticleId);
        if (article == null)
        {
            ModelState.AddModelError("", "回复的文章不存在或已被删除，请刷新后重试");
            return Page();
        }

        await _commentService.SaveCommentAsync(comment);


        var subject = $"[{setting.SiteName}]文章有了新回复";
        var body = $@"你好，{User.Identity.Name}<br/>
你的文章 <b><a href='{Request.ToAbsoluteUrl()}' target='_blank'>{article.Title}</a></b> 有了新回复：
<br/>
{new string('-',100)}
<p>
{comment.Content}
</p>
<p>
昵称：{name}；邮箱：{email}
</p>
您可以点击 <a href='{Request.ToAbsoluteUrl()}#comment-{comment.Id}' target='_blank'>这个链接</a> 查看详情。
<br>
By {setting.SiteName}
";

        await _messageSender.SendAsync(new MailMessage(subject, body, email))
             .ContinueWith(task =>
             {

                 if (task.Exception != null)
                 {
                     //日志
                     _loggerFactory.CreateLogger("CommentEmail").LogError(task.Exception, task.Exception.Message);
                 }
             });


        return RedirectToPage("./Detail", new { id = comment.ArticleId });
    }
        }

<div class="container mt-3">
    <div class="row">
        <div class="col-8">
            <div class="row">
                <div class="col">
                    <h3>@Article.Title</h3>
                    <ul class="list-inline text-muted mt-3 text-sm">
                        <li class="list-inline-item"><i class="fa fa-clock"></i> @Article.CreateTime.ToChineseDateTimeString()</li>
                        <li class="list-inline-item"><i class="fa fa-eye"></i> @Article.ViewCount</li>
                        <li class="list-inline-item"><i class="fa fa-comments"></i> @Article.Comments.Count</li>
                    </ul>
                    <hr />
                    <div class="markdown-body" style="min-height:300px;"></div>
                </div>
            </div>

            <div class="row mt-5">
                <div class="col">
                    @Html.Partial_CommentList(this.Article.Comments.OrderByDescending(m=>m.CreatedTime))
                </div>
            </div>
            @if (GeneralSetting.AllowComment)
            {
                <div class="row">

                    <div class="col">
                        @Html.Partial_CommentForm(this.Article.Id)
                    </div>
                </div>
            }
        </div>
        <div class="col-4">
            @Html.Partial_CategoryList()

            @Html.Partial_ArticleRecommandList(new RecommandArticleViewModel { CategoryId = Article.CategoryId, Title = "相关推荐" })
        </div>
    </div>
</div>
@Html.Hidden("ArticleContent", Html.Raw(Article.Content))
@section styles{
    <link href="https://cdn.bootcss.com/codemirror/5.34.0/codemirror.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/vs.min.css" rel="stylesheet">
}
    @section scripts{
    <script src="https://cdn.bootcss.com/codemirror/5.34.0/codemirror.min.js"></script>
    <script src="https://cdn.bootcss.com/marked/0.3.12/marked.min.js"></script>
    <script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
    @Html.Partial("Shared/_ValidationScripts")
    <script>
        $('.markdown-body').html(marked($('#ArticleContent').val()));
        $('.markdown-body pre code').each(function (i, block) {
            hljs.highlightBlock(block);
        });
    </script>
}